package create.he.utils;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import create.he.common.SQLProxy;
import create.he.common.Execute;
import create.he.entity.JDBCConfig;

public class JDBCUtil {
	/**
	 * 数据库连接属性
	 */
	private JDBCConfig config;
	private Execute instance =null;
	public JDBCUtil() {
		this.config = new JDBCConfig();
		instance = (Execute) new SQLProxy(this.config).getInstance(Execute.class);
	}
	
	public JDBCUtil(JDBCConfig config) {
		this.config = config;
		this.instance = (Execute) new SQLProxy(this.config).getInstance(Execute.class);

	}
	
	/**
	 * 获取一个列表
	 * @param sql 被执行的sql
	 * @return
	 */
	public  List<Map<String ,Object>> findList(String sql) {
		try {
			List<Map<String ,Object>> findList = this.instance.findList(sql,null);
			return findList;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取一个结果
	 * @param sql 被执行的sql
	 * @return
	 */
	public  Map<String ,Object> getMap(String sql) {
		try {
			return instance.getMap(sql,null);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * sql 数据类型 转换为java type
	 * @param sqlType
	 * @return
	 */
	public  String getJavaTypeFromSQLType(String sqlType){
		String javaType = null;
		int index = sqlType.indexOf("(");
		if(index != -1)
			sqlType = sqlType.substring(0, index);
		if(sqlType.equalsIgnoreCase("VARCHAR")||sqlType.equalsIgnoreCase("CHAR")||sqlType.equalsIgnoreCase("TEXT")||sqlType.equalsIgnoreCase("LONGTEXT"))
			javaType = "String";
		else if(sqlType.equalsIgnoreCase("NUMERIC")||sqlType.equalsIgnoreCase("DECIMAL"))
			javaType = "BigDecimal";
		else if(sqlType.equalsIgnoreCase("BIT"))
			javaType = "boolean";
		else if(sqlType.equalsIgnoreCase("TINYINT"))
			javaType = "byte";
		else if(sqlType.equalsIgnoreCase("SAMLLINT"))
			javaType = "short";
		else if(sqlType.equalsIgnoreCase("INTEGER")||sqlType.equalsIgnoreCase("int")||sqlType.equalsIgnoreCase("mediumint"))
			javaType = "int";
		else if(sqlType.equalsIgnoreCase("BIGINT"))
			javaType = "long";
		else if(sqlType.equalsIgnoreCase("REAL"))
			javaType = "float";
		else if(sqlType.equalsIgnoreCase("FLOAT")||sqlType.equalsIgnoreCase("double"))
			javaType = "double";
		else if(sqlType.equalsIgnoreCase("binary")||sqlType.equalsIgnoreCase("varbinary")||sqlType.equalsIgnoreCase("longvarbinary"))
			javaType = "byte[]";
		else if(sqlType.equalsIgnoreCase("date"))
			javaType = "Date";
		else if(sqlType.equalsIgnoreCase("time"))
			javaType = "Time";
		else if(sqlType.equalsIgnoreCase("datetime")||sqlType.equalsIgnoreCase("timestamp"))
			javaType = "Timestamp";
		return javaType;
	}
}
